<template>
  <div class="message-list-page">
    <div class="list-header">
      <HeaderFilter ref="filterRef" />
      <el-dropdown trigger="click" popper-class="msg-dropdown">
        <div class="publish-btn">
          <img
            src="@/assets/images/message/icon-add.svg?url"
            class="icon-add"
          />
          发布通知
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="msgType in MSG_TYPE_LIST.slice(1)"
              :key="msgType.value"
              @click="publishMessage(msgType.value)"
              >{{ msgType.label }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <el-scrollbar
      v-if="messageList.length > 0"
      v-loading="isLoading"
      class="list-container"
      height="83.8vh"
      @scroll="onScrollList"
      ref="scrollbarRef"
    >
      <MessageItem
        v-for="msg in messageList"
        :key="msg.message_id"
        :item="msg"
        @editMessage="editMessage"
        @deleteMessage="deleteMessage"
      />
    </el-scrollbar>
    <el-empty
      v-else
      class="list-container"
      style="height: 90vh"
      description="暂无数据"
    />
  </div>
  <MessageDrawer
    v-if="drawerVisible"
    v-model:visible="drawerVisible"
    :msgType="msgType"
    @updateMessageList="updateMessageList"
    :editInfo="editInfo"
  />
  <TipAlert
    v-if="tipAlertVisible"
    :content="tipText"
    @close="tipAlertVisible = false"
    @confirm="onComfirmDelete"
  />
</template>

<script setup>
import HeaderFilter from '@/views/message-center/components/HeaderFilter.vue'
import MessageDrawer from '@/views/message-center/components/MessageDrawer.vue'
import MessageItem from '@/views/message-center/components/MessageItem.vue'
import TipAlert from '@/components/TipAlert.vue'
import { ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { MSG_TYPE_LIST, MsgStatusEnum } from '../constant'
import { reqGetMsgList, reqGetMsgDetail, reqDeleteMsg } from '@/apis/message'
import { useAuthStore } from '@/stores'

const authStore = useAuthStore()
const { userInfo, nowGlobalRole } = storeToRefs(authStore)

const drawerVisible = ref(false)

// 通知筛选条件
const filterRef = ref(null)
const filterOptions = computed(() => filterRef.value?.filterOptions)
watch(
  filterOptions,
  val => {
    if (val) {
      console.log('通知筛选 =>', val)
      updateMessageList()
    }
  },
  {
    deep: true
  }
)

// 通知类型
const msgType = ref()

// 打开发布通知抽屉
const publishMessage = v => {
  // 清空编辑信息
  editInfo.value = {}
  drawerVisible.value = true
  msgType.value = v
}

// 请求消息列表
const messageList = ref([])
const curPage = ref(1)
const total = ref(0)
const totalPage = computed(() => Math.ceil(total.value / limit.value))
const limit = ref(10)
const isLoading = ref(false)
const reset = () => {
  curPage.value = 1
  total.value = 0
  messageList.value = []
}
const getMessageList = async () => {
  if (total.value && curPage.value > totalPage.value) return
  isLoading.value = true
  const params = {
    page: curPage.value,
    page_size: limit.value,
    release: filterOptions.value.status,
    type: filterOptions.value.type || undefined,
    target_type: filterOptions.value.receiver[0] || undefined,
    class_id: filterOptions.value.receiver[2],
    user_id: userInfo.value.userId,
    role_code: nowGlobalRole.value.role_code,
    school_id: userInfo.value.school_id
  }
  const res = await reqGetMsgList(params)
  total.value = res.count
  messageList.value.push(...res.list)
  curPage.value++
  isLoading.value = false
}

// 重新获取消息列表
const updateMessageList = () => {
  reset()
  getMessageList()
}

// 滚动到底部加载更多
const scrollbarRef = ref(null)
const onScrollList = e => {
  const { offsetHeight, scrollHeight } = scrollbarRef.value.wrapRef
  if (offsetHeight + e.scrollTop >= scrollHeight) {
    getMessageList()
  }
}

const editInfo = ref({})
// 获取未发布的消息详情进行编辑
const getUnpublishedMsgDetail = async message_id => {
  const params = {
    message_id,
    release: MsgStatusEnum.UNPUBLISHED
  }
  const res = await reqGetMsgDetail(params)
  editInfo.value = res
}
// 显示编辑通知抽屉
const editMessage = async msgId => {
  await getUnpublishedMsgDetail(msgId)
  drawerVisible.value = true
  msgType.value = editInfo.value.type
}

// 显示删除提示弹框
const tipAlertVisible = ref(false)
const tipText = ref('')
let message_id
const deleteMessage = msgId => {
  if (filterOptions.value.status === MsgStatusEnum.PUBLISHED) {
    tipText.value = '删除后学生不能查看该通知，确定删除吗？'
  } else {
    tipText.value = '确定删除吗？'
  }
  tipAlertVisible.value = true
  message_id = msgId
}
const onComfirmDelete = async () => {
  tipAlertVisible.value = false
  const res = await reqDeleteMsg({ message_id })
  console.log('onComfirmDelete =>', message_id, res)
  if (res) {
    ElMessage.success('删除成功')
    updateMessageList()
  }
}
</script>

<style lang="less" scoped>
.message-list-page {
  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    white-space: nowrap;
    margin-bottom: 20px;

    .publish-btn {
      width: 116px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      background: #428fff;
      border-radius: 3px 3px 3px 3px;
      user-select: none;
      cursor: pointer;
      .icon-add {
        margin-right: 4px;
      }
    }
  }

  .list-container {
    padding: 30px;
    border-radius: 15px;
    background-color: #fff;
    :deep(.el-loading-mask) {
      z-index: 500;
    }
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.msg-dropdown {
  user-select: none;
  .el-dropdown-menu {
    .el-dropdown-menu__item {
      padding: 5px 26px;
      font-size: 16px;
    }
  }
}
</style>
